'use client';

import { useState } from 'react';

interface Member {
  id: string;
  name: string;
  role: 'professor' | 'phd' | 'master' | 'undergraduate' | 'alumni';
  title?: string;
  email?: string;
  phone?: string;
  avatar?: string;
  bio?: string;
  researchAreas?: string[];
  homepage?: string;
  isActive: boolean;
  joinDate?: string;
}

const roleLabels = {
  professor: '教授',
  phd: '博士生',
  master: '硕士生',
  undergraduate: '本科生',
  alumni: '毕业生'
};

export default function MembersPage() {
  const [members, setMembers] = useState<Member[]>([
    {
      id: '1',
      name: '张教授',
      role: 'professor',
      title: '实验室主任',
      email: 'zhang@university.edu',
      phone: '123-456-7890',
      bio: '机器人技术专家，从事机器人控制与人工智能研究20年。',
      researchAreas: ['机器人控制', '人工智能', '计算机视觉'],
      isActive: true,
      joinDate: '2010-01-01'
    },
    {
      id: '2',
      name: '李博士',
      role: 'phd',
      email: 'li@university.edu',
      bio: '专注于机械臂运动控制研究。',
      researchAreas: ['机械臂控制', '运动规划'],
      isActive: true,
      joinDate: '2020-09-01'
    },
    {
      id: '3',
      name: '王硕士',
      role: 'master',
      email: 'wang@university.edu',
      bio: '研究方向为计算机视觉在机器人中的应用。',
      researchAreas: ['计算机视觉', '深度学习'],
      isActive: true,
      joinDate: '2022-09-01'
    }
  ]);

  const [showAddForm, setShowAddForm] = useState(false);
  const [editingMember, setEditingMember] = useState<Member | null>(null);
  const [formData, setFormData] = useState<Partial<Member>>({
    name: '',
    role: 'undergraduate',
    title: '',
    email: '',
    phone: '',
    bio: '',
    researchAreas: [],
    homepage: '',
    isActive: true,
    joinDate: new Date().toISOString().split('T')[0]
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingMember) {
      // 更新成员
      setMembers(members.map(member => 
        member.id === editingMember.id 
          ? { ...member, ...formData }
          : member
      ));
      setEditingMember(null);
    } else {
      // 添加新成员
      const { id, ...memberData } = formData as Member;
      const newMember: Member = {
        id: Date.now().toString(),
        ...memberData
      };
      setMembers([...members, newMember]);
    }
    
    setShowAddForm(false);
    setFormData({
      name: '',
      role: 'undergraduate',
      title: '',
      email: '',
      phone: '',
      bio: '',
      researchAreas: [],
      homepage: '',
      isActive: true,
      joinDate: new Date().toISOString().split('T')[0]
    });
  };

  const handleEdit = (member: Member) => {
    setEditingMember(member);
    setFormData({
      name: member.name,
      role: member.role,
      title: member.title || '',
      email: member.email || '',
      phone: member.phone || '',
      bio: member.bio || '',
      researchAreas: member.researchAreas || [],
      homepage: member.homepage || '',
      isActive: member.isActive,
      joinDate: member.joinDate
    });
    setShowAddForm(true);
  };

  const handleDelete = (id: string) => {
    if (confirm('确定要删除这个成员吗？')) {
      setMembers(members.filter(member => member.id !== id));
    }
  };

  const handleResearchAreaChange = (value: string) => {
    const areas = value.split(',').map(area => area.trim()).filter(area => area);
    setFormData({ ...formData, researchAreas: areas });
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">团队成员管理</h1>
          <p className="text-gray-600 mt-1">管理实验室成员信息</p>
        </div>
        <button
          onClick={() => setShowAddForm(true)}
          className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
        >
          ➕ 添加成员
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-blue-600">
            {members.filter(m => m.role === 'professor').length}
          </div>
          <div className="text-sm text-gray-600">教授</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-purple-600">
            {members.filter(m => m.role === 'phd').length}
          </div>
          <div className="text-sm text-gray-600">博士生</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-green-600">
            {members.filter(m => m.role === 'master').length}
          </div>
          <div className="text-sm text-gray-600">硕士生</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-yellow-600">
            {members.filter(m => m.role === 'undergraduate').length}
          </div>
          <div className="text-sm text-gray-600">本科生</div>
        </div>
      </div>

      {/* Members List */}
      <div className="bg-white rounded-lg shadow">
        <div className="px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-semibold">成员列表</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  成员信息
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  角色/职位
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  联系方式
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  研究领域
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {members.map((member) => (
                <tr key={member.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      <div className="h-10 w-10 flex-shrink-0">
                        <div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                          <span className="text-blue-600 font-medium">
                            {member.name.charAt(0)}
                          </span>
                        </div>
                      </div>
                      <div className="ml-4">
                        <div className="text-sm font-medium text-gray-900">
                          {member.name}
                        </div>
                        {member.title && (
                          <div className="text-sm text-gray-500">{member.title}</div>
                        )}
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                      member.role === 'professor' ? 'bg-purple-100 text-purple-800' :
                      member.role === 'phd' ? 'bg-blue-100 text-blue-800' :
                      member.role === 'master' ? 'bg-green-100 text-green-800' :
                      'bg-yellow-100 text-yellow-800'
                    }`}>
                      {roleLabels[member.role]}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <div>{member.email}</div>
                    {member.phone && <div>{member.phone}</div>}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 max-w-xs">
                    <div className="truncate">
                      {member.researchAreas?.join(', ') || '暂无'}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                      member.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {member.isActive ? '在职' : '离职'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <div className="flex space-x-2">
                      <button
                        onClick={() => handleEdit(member)}
                        className="text-blue-600 hover:text-blue-800"
                      >
                        ✏️
                      </button>
                      <button
                        onClick={() => handleDelete(member.id)}
                        className="text-red-600 hover:text-red-800"
                      >
                        🗑️
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit Form Modal */}
      {showAddForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold">
                {editingMember ? '编辑成员' : '添加成员'}
              </h2>
              <button
                onClick={() => {
                  setShowAddForm(false);
                  setEditingMember(null);
                }}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    姓名 *
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    角色 *
                  </label>
                  <select
                    required
                    value={formData.role}
                    onChange={(e) => setFormData({ ...formData, role: e.target.value as any })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="professor">教授</option>
                    <option value="phd">博士生</option>
                    <option value="master">硕士生</option>
                    <option value="undergraduate">本科生</option>
                    <option value="alumni">毕业生</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    职位/头衔
                  </label>
                  <input
                    type="text"
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    邮箱
                  </label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    电话
                  </label>
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    加入日期
                  </label>
                  <input
                    type="date"
                    value={formData.joinDate}
                    onChange={(e) => setFormData({ ...formData, joinDate: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  研究领域（用逗号分隔）
                </label>
                <input
                  type="text"
                  value={formData.researchAreas?.join(', ') || ''}
                  onChange={(e) => handleResearchAreaChange(e.target.value)}
                  placeholder="机器人控制, 人工智能, 计算机视觉"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  个人简介
                </label>
                <textarea
                  value={formData.bio}
                  onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                  rows={3}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  个人主页
                </label>
                <input
                  type="url"
                  value={formData.homepage}
                  onChange={(e) => setFormData({ ...formData, homepage: e.target.value })}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="isActive"
                  checked={formData.isActive}
                  onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
                  className="mr-2"
                />
                <label htmlFor="isActive" className="text-sm font-medium text-gray-700">
                  当前在职
                </label>
              </div>

              <div className="flex justify-end space-x-3 pt-4">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddForm(false);
                    setEditingMember(null);
                  }}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  {editingMember ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}